package com.example.coursemgt.service;

import com.example.coursemgt.dao.CourseDao;
import com.example.coursemgt.model.Course;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class AsyService {
    private final static Logger log = LoggerFactory.getLogger(AsyService.class);
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private CourseDao courseDao;

    @Async
    public void findCourseByIdAsy(Long id) {
        Course course;
        int count = 0;
        while (count <= 15) {
            count++;
            String key = "course_" + id;
            ValueOperations<String, Course> operations = redisTemplate.opsForValue();
            //判断redis中是否有键为key的缓存
            boolean hasKey = redisTemplate.hasKey(key);

            if (hasKey) {
                course = operations.get(key);
                log.info("fetch data from redis:" + course.getName());
            } else {
                course = courseDao.findCourseById(id);
                log.info("fetch data from pg:" + course.getName());
                //写入缓存
                operations.set(key, course, 3, TimeUnit.MINUTES);
            }
        }
    }
}
